package com.dx.utils;




import com.dx.result.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.HashMap;

/**
 * 基于Jackson的JSON工具类
 */
public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将JSON字符串反序列化为HashMap
     * @param jsonString JSON字符串
     * @return HashMap对象
     */
    public static HashMap<String, Object> toHashMap(String jsonString) {
        try {
            if (jsonString == null || jsonString.trim().isEmpty()) {
                return new HashMap<>();
            }
            return objectMapper.readValue(jsonString, new TypeReference<HashMap<String, Object>>() {});
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON string: " + e.getMessage(), e);
        }
    }

    /**
     * 将HashMap序列化为JSON字符串
     * @param map HashMap对象
     * @return JSON字符串
     */
    public static String toJson(HashMap<String, Object> map) {
        try {
            if (map == null) {
                return "{}";
            }
            return objectMapper.writeValueAsString(map);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert map to JSON string: " + e.getMessage(), e);
        }
    }

    /**
     * 将JSON字符串反序列化为指定类型的对象
     * @param jsonString JSON字符串
     * @param clazz 目标类的Class对象
     * @param <T> 目标类型
     * @return 反序列化后的对象
     */
    public static <T> T toObject(String jsonString, Class<T> clazz) {
        try {
            if (jsonString == null || jsonString.trim().isEmpty()) {
                return null;
            }
            return objectMapper.readValue(jsonString, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse JSON string to object: " + e.getMessage(), e);
        }
    }

}
